﻿namespace Revit同步插件.MEP建模
{

  using Autodesk.Revit.DB;
  using Autodesk.Revit.UI;
  using System;
  using System.Data;

  [Autodesk.Revit.Attributes.Transaction(Autodesk.Revit.Attributes.TransactionMode.Manual)]
  internal class 创建所有管件 : IExternalCommand
  {


    UIApplication _uiapp;
    public Autodesk.Revit.UI.Result Execute(Autodesk.Revit.UI.ExternalCommandData commandData,
    ref string message,
    Autodesk.Revit.DB.ElementSet elements)
    {

      try
      {
        _uiapp = commandData.Application;
        UIDocument uidoc = _uiapp.ActiveUIDocument;
        Document doc = uidoc.Document;

        Level activeLevel = doc.ActiveView.GenLevel;

        var mepSymCollection = doc.Query<FamilySymbol>(new ElementFilter[] {
          new LogicalOrFilter( 
            new ElementFilter[]{
                new ElementCategoryFilter(BuiltInCategory.OST_PipeFitting),
                new ElementCategoryFilter(BuiltInCategory.OST_PipeAccessory),
            }
            ),
          new ElementIsElementTypeFilter()
        }) ;

        int amount = mepSymCollection.Count;
        int size = (int)Math.Ceiling(Math.Sqrt(amount));
        double cellSize = 1000 / 304.8;
        DataTable errTable = new DataTable();
        errTable.Columns.Add("名称", typeof(string));
        errTable.Columns.Add("", typeof(string));
        errTable.Columns.Add("", typeof(string));
        using (Transaction t = new Transaction(doc, $"管件阵列 {size}x{size}"))
        {
          t.Start();
          var iter = mepSymCollection.GetEnumerator();
          int count = 0;
          while(iter.MoveNext())
          {

            int row = count % size;
            int col = count / size;
            FamilySymbol cur = iter.Current;
            XYZ pt = new XYZ( row * cellSize, col*cellSize,0);
            try
            {
              if (!cur.IsActive)
              {
                cur.Activate();
              }
              var instance = doc.Create.NewFamilyInstance(pt, cur, activeLevel, Autodesk.Revit.DB.Structure.StructuralType.NonStructural);
            }
            catch (Exception)
            {
            
            }

            TextNote.Create(doc, doc.ActiveView.Id, pt - XYZ.BasisY, cur.Name, doc.GetDefaultElementTypeId(ElementTypeGroup.TextNoteType));
            count++;
          }
          t.Commit();
        }




        return Autodesk.Revit.UI.Result.Succeeded;
      }
      catch (System.Exception ex)
      {
        message = ex.Message;
        return Autodesk.Revit.UI.Result.Failed;
      }
    }
  }

}
